<template>
	<a-card :bordered="false" style="margin-bottom: 10px">
		<a-space :size="16">
			<a-select v-model:value="searchForm.selectTime" allowClear placeholder="请选择领取时间" class="w-[240px]">
				<a-select-option value="1">今天</a-select-option>
				<a-select-option value="0">昨天</a-select-option>
				<a-select-option value="2">最近三天</a-select-option>
			</a-select>
			<a-select v-model:value="searchForm.receiveWay" allowClear placeholder="请选择获取方式" class="w-[240px]">
				<a-select-option value="0">我领取的</a-select-option>
				<a-select-option value="1">同事分配的</a-select-option>
			</a-select>
			<!-- <a-select v-model:value="searchForm.post" allowClear placeholder="请选择职位" class="w-[240px]">
				<a-select-option :value="0">法人</a-select-option>
				<a-select-option :value="1">关键决策人</a-select-option>
			</a-select> -->
			<a-input v-model:value="searchForm.post" allowClear placeholder="请输入职位" @pressEnter="getData"></a-input>
			<a-button type="primary" @click="getData">查询</a-button>
		</a-space>
	</a-card>
	<a-card :bordered="false" style="margin-bottom: 10px">
		<a-space :size="16" class="mb-6">
			<div>批量操作</div>
			<a-button v-if="hasPerm('bizTokerBatchAllocate')" type="primary" @click="toDivide">批量分配企业</a-button>
			<a-button v-if="hasPerm('bizTokerBatchDelete')" type="primary" @click="toDeletePersons('batch')"
				>批量删除</a-button
			>
		</a-space>
		<a-table
			:columns="companyColumns"
			:data-source="list"
			:showHeader="false"
			:pagination="false"
			:row-key="(record) => record.customerCode"
			:row-selection="{ selectedRowKeys: selectedCompanys, onChange: onSelectCompany }"
		>
			<template #bodyCell="{ column, record }">
				<template v-if="column.dataIndex === 'customerName'">
					<div class="flex justify-between">
						<a-space :size="16">
							<div>{{ record.customerName }}</div>
							<a-tag color="var(--disabled-color)">未转化</a-tag>
						</a-space>
						<a-space :size="4">
							<a-button v-if="hasPerm('bizTokerTransferClue') && record.expand" type="link" @click="toTransfer(3)"
								>转线索</a-button
							>
							<a-button v-if="hasPerm('bizTokerTransfer') && record.expand" type="link" @click="toTransfer(0)"
								>转客户</a-button
							>
							<a-button v-if="hasPerm('bizTokerDelete') && record.expand" type="link" @click="toDeleteClaim(record.id)"
								>删除</a-button
							>
							<a-button type="link" @click="expandUp(record)">
								{{ record.expand ? '收起' : '展开' }}
							</a-button>
						</a-space>
					</div>
					<a-table
						v-if="record.expand"
						ref="table"
						:columns="columns"
						:data-source="personData"
						:expand-row-by-click="true"
						bordered
						:pagination="false"
						:row-key="(record) => record.id"
						:row-selection="{ selectedRowKeys: selectedContacts, onChange: onSelectChange }"
					>
						<template #bodyCell="{ column: columnVal, record: recordVal }">
							<template v-if="columnVal.dataIndex === 'contactsPhone'">
								<a-button
									type="link"
									@click="
										onPhoneConnect(recordVal.id, record.customerCode, recordVal.contactsPhone, record.customerName)
									"
									>{{ recordVal.contactsPhone }}</a-button
								>
							</template>
							<template v-if="columnVal.dataIndex === 'accessWay'">
								<a-space :size="16">
									<span v-if="recordVal.accessWay === 0">我领取的</span>
									<span v-else>同事分配的</span>
								</a-space>
							</template>
							<template v-if="columnVal.dataIndex === 'action'">
								<a-space :size="16">
									<a v-if="hasPerm('bizTokerDeleteLinker')" @click="toDeletePersons(recordVal.id)">删除</a>
								</a-space>
							</template>
						</template>
					</a-table>
				</template>
			</template>
		</a-table>
		<div class="text-right pt-6">
			<a-pagination
				size="small"
				:total="pagination.total"
				show-size-changer
				:page-size-options="['10', '20', '30']"
				:show-total="(total, range) => `${range[0]}-${range[1]} 共 ${total} 条`"
				v-model:pageSize="pagination.size"
				v-model:current="pagination.current"
				@change="pageChange"
				@showSizeChange="pageChange"
			>
				<template #buildOptionText="props">
					<span>{{ props.value }}条/页</span>
				</template>
			</a-pagination>
		</div>
	</a-card>
	<!-- 批量分配企业 -->
	<a-modal v-model:visible="divideVisible" title="分配企业" :width="600" @ok="confirmDivide" @cancel="cancelDivide">
		<div class="flex gap-2">
			<div class="w-[200px] max-h-[360px] overflow-auto">
				选择部门
				<a-tree
					v-if="treeData.length > 0"
					v-model:selectedKeys="treeKeys"
					v-model:expandedKeys="defaultExpandedKeys"
					:tree-data="treeData"
					:field-names="treeFieldNames"
					@select="treeSelect"
				>
				</a-tree>
			</div>
			<div class="flex-1">
				<div>员工姓名</div>
				<a-input-search
					v-model:value="searchKey"
					placeholder="请输入"
					@search="treeSelect(treeKeys)"
					style="width: 100%"
				/>
				<div class="mt-1 max-h-[300px] overflow-auto">
					<a-checkbox-group v-model:value="selectUser" @change="toUserChange">
						<div v-for="item in userList" :key="item.value">
							<a-checkbox :value="item.value">{{ item.label }}</a-checkbox>
						</div>
					</a-checkbox-group>
				</div>
			</div>
		</div>
	</a-modal>
	<!-- 转客户 -->
	<follow-modal
		v-if="transferVisible"
		:title="transferType ? '转线索' : '转客户'"
		:type="transferType"
		:customerCode="currentCoustomerCode"
		:list="transferList"
		v-model:visible="transferVisible"
		:personData="transferPersons"
		@finished="getData"
	/>
</template>

<script setup>
	import claimApi from '@/api/biz/claimApi'
	import orgApi from '@/api/biz/bizOrgApi'
	import usersApi from '@/api/biz/bizUserApi'
	import { message, Modal } from 'ant-design-vue'
	import { isEmpty } from 'lodash-es'
	import followModal from './followModal.vue'
	import { globalStore } from '@/store'

	const store = globalStore()

	/**
	 * ====================
	 *       基本逻辑
	 * ====================
	 */
	onBeforeMount(() => {
		getData()
	})
	// 左侧树查询
	const treeData = ref([])
	const defaultExpandedKeys = ref([])
	const treeKeys = ref([])
	const treeFieldNames = { children: 'children', title: 'name', key: 'id' }
	orgApi.orgTree().then((res) => {
		if (res !== null) {
			treeData.value = res
			treeSelect([res[0].id])
			if (isEmpty(defaultExpandedKeys.value)) {
				// 默认展开2级
				treeData.value.forEach((item) => {
					// 因为0的顶级
					if (item.parentId === '0') {
						defaultExpandedKeys.value.push(item.id)
						// 取到下级ID
						if (item.children) {
							item.children.forEach((items) => {
								defaultExpandedKeys.value.push(items.id)
							})
						}
					}
				})
			}
		}
	})
	// 点击树查询
	const userList = ref([])
	const selectUser = ref([])
	const searchKey = ref('')
	const treeSelect = (selectedKeys) => {
		const params = {
			orgId: selectedKeys[0],
			searchKey: searchKey.value
		}
		usersApi.userSelector(params).then((res) => {
			userList.value = res.map((item) => {
				return {
					label: item.name,
					value: `${item.id}&${item.name}`
				}
			})
		})
	}
	const toUserChange = (select) => {
		selectUser.value = [select.at(-1)]
	}
	const companyColumns = [
		{
			title: '公司名称',
			dataIndex: 'customerName'
		}
	]
	const list = ref([])
	const currentCompanyId = ref()
	const currentCoustomerCode = ref()
	const searchForm = ref({
		selectTime: undefined,
		receiveWay: undefined,
		post: undefined
	})
	const pagination = ref({
		size: 10,
		current: 1,
		total: 0
	})

	const getCompanyPersons = (code) => {
		const param = {
			code: code
		}
		claimApi.getCompanyPersons(param).then((res) => {
			personData.value = res
			personData.value.forEach((item) => {
				item.contactsName = item.contactsName ? item.contactsName : '—'
			})

			// store.setTransferPersonDataAndList(personData.value, [])
		})
	}

	const getData = () => {
		const parameter = {
			current: pagination.value.current,
			size: pagination.value.size,
			...searchForm.value
		}
		claimApi.getClaimList(parameter).then((res) => {
			pagination.value.total = res.total
			if (res.records.length > 0) {
				list.value = res.records.map((item) => {
					return {
						...item,
						expand: false
					}
				})
				list.value[0].expand = true
				currentCompanyId.value = list.value[0].id
				currentCoustomerCode.value = list.value[0].customerCode

				getCompanyPersons(list.value[0].customerCode)
			} else {
				list.value = res.records
			}
		})
	}
	const pageChange = (cur, size) => {
		pagination.value.size = size
		pagination.value.current = cur
		getData()
	}
	/**
	 * 多选企业
	 */
	const selectedCompanys = ref([])
	const onSelectCompany = (selectedRowKeys) => {
		selectedCompanys.value = selectedRowKeys
	}
	const columns = [
		{
			title: '联系人',
			dataIndex: 'contactsName',
			width: 350
		},
		{
			title: '职位',
			dataIndex: 'contactsPost',
			width: 350
		},
		{
			title: '联系方式',
			dataIndex: 'contactsPhone',
			width: 350
		},
		{
			title: '获取方式',
			dataIndex: 'accessWay',
			width: 350
		},
		{
			title: '获取时间',
			dataIndex: 'receiveTime',
			width: 350
		},
		{
			title: '操作',
			dataIndex: 'action',
			align: 'center',
			fixed: 'right',
			width: '300px'
		}
	]
	const personData = ref([])
	/**
	 * 展开收起逻辑
	 * @param {*} record
	 */
	const expandUp = (record) => {
		if (record.expand) {
			record.expand = false
		} else {
			if (currentCoustomerCode.value !== record.customerCode) {
				selectedContacts.value = []
				personData.value = []
				currentCoustomerCode.value = record.customerCode

				getCompanyPersons(record.customerCode)
			}
			list.value.map((item) => {
				item.expand = false
			})
			record.expand = true
		}
	}

	/**
	 * 选择联系人
	 */
	const selectedContacts = ref([])
	const onSelectChange = (selectedRowKeys) => {
		selectedContacts.value = selectedRowKeys
	}

	/**
	 * ====================
	 *       分配企业
	 * ====================
	 */
	const divideVisible = ref(false)
	const toDivide = () => {
		if (selectedCompanys.value.length <= 0) {
			message.warning('请先选择企业')
			return
		}
		divideVisible.value = true
	}
	/**
	 * 确认分配
	 */
	const confirmDivide = () => {
		if (selectUser.value.length <= 0) {
			message.warning('请选择分配人')
			return
		}
		const arr = selectUser.value[0].split('&')
		const params = {
			id: arr[0],
			userName: arr[1],
			list: selectedCompanys.value
		}
		claimApi.divideCompany(params).then(() => {
			selectUser.value = []
			searchKey.value = ''
			divideVisible.value = false
			getData()
		})
	}
	/**
	 * 取消分配
	 */
	const cancelDivide = () => {
		selectedCompanys.value = []
		divideVisible.value = false
	}
	/**
	 * ====================
	 *       转客户/转线索
	 * ====================
	 */
	const transferType = ref(0) // 0-转客户 3-转线索
	const transferVisible = ref(false)
	const transferPersons = ref([])
	const transferList = ref([])
	const setTransferPersonsAndList = () => {
		if (selectedContacts.value.length === 0) {
			transferPersons.value = personData.value
			transferList.value = []
		} else {
			transferPersons.value = personData.value.filter((item) => selectedContacts.value.indexOf(item.id) >= 0)
			transferList.value = selectedContacts.value
		}

		store.setTransferPersonDataAndList(transferPersons.value, transferList.value)
	}
	const toTransfer = (type) => {
		transferType.value = type
		setTransferPersonsAndList()
		transferVisible.value = true
	}
	/**
	 * ====================
	 *       删除操作
	 * ====================
	 */
	/**
	 * 删除企业下的联系人
	 */
	const deletePersons = (pramas) => {
		claimApi.deleteCompanyPersons(pramas).then(() => {
			selectedContacts.value = selectedContacts.value.filter((item) => pramas.list.includes(item.id))

			getCompanyPersons(currentCoustomerCode.value)
		})
	}
	const toDeletePersons = (id) => {
		if (id === 'batch' && selectedContacts.value.length === 0) {
			message.warning('批量删除请先选择企业下的联系人')
			return
		}
		Modal.confirm({
			title: '提示',
			content: '确认删除吗?',
			okText: '确认',
			onOk: () => {
				const params = {
					customerCode: currentCoustomerCode.value,
					list: id === 'batch' ? selectedContacts.value : [id]
				}
				deletePersons(params)
			},
			closable: true,
			cancelText: '取消'
		})
	}
	/**
	 * 删除领取企业
	 */
	const toDeleteClaim = (id) => {
		Modal.confirm({
			title: '提示',
			content: '确认删除吗?',
			okText: '确认',
			onOk: () => {
				claimApi.deleteCompany({ id }).then(() => {
					pagination.value.current = 1
					getData()
				})
			},
			closable: true,
			cancelText: '取消'
		})
	}

	/**
	 * 拨打电话
	 */
	const onPhoneConnect = (id, code, phone, name) => {
		setTransferPersonsAndList()
		store.dashboardNode?.open({ id, code, phone, name, type: 1 })
	}

	const transferStatus = computed(() => store.transferStatus)
	watch(transferStatus, (newVal, oldVal) => {
		if (newVal) {
			toTransfer(0)
		}
	})
</script>

<style lang="less" scoped>
	.cardImp {
		margin-right: 10px;
	}
	.ant-form-item {
		margin-bottom: 0 !important;
	}
	.snowy-buttom-left {
		margin-left: 8px;
	}
	//:deep(.ant-pagination.mini .ant-pagination-options-size-changer) {
	//	width: 74px;
	//}
</style>
